AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
--include('entities/base_wire_entity/init.lua')
include( 'shared.lua' )

function ENT:Initialize()

	self.Entity:SetModel( "models/GIMP/cannon_cannon2.mdl" )
	self.Entity:SetName("Craplauncher")
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )
    	
	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
		phys:EnableGravity(true)
		phys:EnableDrag(false)
		phys:EnableCollisions(true)
		phys:SetMass( 2000 )
	end
	
	local ent = ents.Create( "Scorchpoint" )
	ent:SetPos( self:GetPos() + (self:GetForward() * -4) + (self:GetUp() * 14) )
	ent:Spawn()
	ent.Par = self
	ent:SetParent(self)
	
	constraint.Weld(self,ent)
	
end


function ENT:Think()
	

end

function ENT:SpawnFunction( ply, tr )

	if ( !tr.Hit ) then return end
	
	local SpawnPos = tr.HitPos + tr.HitNormal * 16 + Vector(0,0,50)
	
	local ent = ents.Create( "CraplauncherPlanked" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	ent.SPL = ply
	
	return ent
	
end

function ENT:Use( activator, caller )

end

function ENT:Touch( ent )
	
end

function ENT:Scorchy()
	local T = ents.CustomFindInBox(self:GetPos() + (self:GetUp() * 5) + (self:GetForward() * -15),Vector(35,10,10),self:GetAngles())
	for k,e in pairs(T) do
		if e && e:IsValid() && e != self then
			physi = e:GetPhysicsObject()
			if physi && physi:IsValid() then
				physi:ApplyForceCenter(self:GetForward() * -5000 * physi:GetMass() + self:GetUp() * math.random(-50,50) + self:GetRight() * math.random(-50,50))
			end
			e:TakeDamage(10,self,self)
		end
	end
	
	self:GetPhysicsObject():ApplyForceCenter(self:GetForward() * 500 * self:GetPhysicsObject():GetMass())
	
	util.BlastDamage(self.Entity, self.Entity, self:GetPos() + (self:GetForward() * 0), 10, 10 )
	util.BlastDamage(self.Entity, self.Entity, self:GetPos() + (self:GetForward() * -10), 10, 10 )
	util.BlastDamage(self.Entity, self.Entity, self:GetPos() + (self:GetForward() * -20), 10, 10 )
	util.BlastDamage(self.Entity, self.Entity, self:GetPos() + (self:GetForward() * -30), 20, 20 )
	
	local effectdata = EffectData()
	effectdata:SetOrigin( self:GetPos() + self:GetForward() * -30 + self:GetUp() * 8 )
	effectdata:SetScale( 1 )
	effectdata:SetMagnitude( 1 )
	util.Effect( "Explosion", effectdata )	
end

function ents.CustomFindInBox(Pos,Size,Ang)
			
	local XB, YB, ZB = Size.x * 0.5, Size.y * 0.5, Size.z * 0.5
	local Results = {}
	for k,e in pairs(ents.GetAll()) do
		local EP = e:GetPos()
		
		local EPL = WorldToLocal( EP, Angle(0,0,0), Pos, Ang)
		local X,Y,Z = EPL.x, EPL.y, EPL.z
		
		if X <= XB && X >= -XB && Y <= YB && Y >= -YB && Z <= ZB && Z >= -ZB then
			table.insert(Results, e)
		end
	end
	return Results
	
end